#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void writer(int wfd)
{
    char outbuffer[128] = {0};
    int cnt = 0;
    while (1)
    {
        sprintf(outbuffer, "message:%s, count:%d\n", "hello father, I am child", cnt);
        cnt++;
        // 写入数据
        write(wfd, outbuffer, strlen(outbuffer));
        sleep(1);
    }
}

void reader(int rfd)
{
    char buffer[1024] = {0};
    while (1)
    {
        // 读取数据
        read(rfd, buffer, sizeof(buffer) - 1);
        printf("father recv a message:%s", buffer);
        sleep(1);
    }
}
int main()
{
    int pipefd[2];
    // 1.申请管道
    int n = pipe(pipefd);
    // 2.fork子进程
    ssize_t id = fork();
    if (id == 0)
    {
        // child:w
        // 3.关闭读管道
        close(pipefd[0]);
        writer(pipefd[1]);
        exit(0);
    }
    // parent:r
    close(pipefd[1]);
    reader(pipefd[0]);
    wait(NULL);
    return 0;
}